package org.apache.ibatis.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * 加载mybatis配置文件的类
 * 封装了ClassLoader，即ClassLoaderWrapper类，主要加载资源的执行者
 * @author xieqiaofu
 * Create time: 2019/10/08
 **/
public class Resources {

    /**
     * 用静态成员的方式初始化ClassLoaderWrapper
     */
    private static ClassLoaderWrapper classLoaderWrapper = new ClassLoaderWrapper();

    /**
     * 字符集，主要用于获取getResourceAsReader时需要指定字符集
     */
    private static Charset charset;

    public static Charset getCharset() {
        return Resources.charset;
    }

    public static void setCharset(Charset charset) {
        Resources.charset = charset;
    }

    /**
     * 用户自己传入的classLoader，设置为ClassLoaderWrapper的defaultClassLoader
     * @param defaultClassLoader
     */
    public static void setDefaultClassLoader(ClassLoader defaultClassLoader) {
        classLoaderWrapper.defaultClassLoader = defaultClassLoader;
    }

    public static ClassLoader getDefaultClassLoader() {
        return classLoaderWrapper.defaultClassLoader;
    }

    /**
     * 从CLASSPATH下获取URL
     * @param resource
     * @return
     * @throws IOException
     */
    public static URL getResourceURL(String resource) throws IOException {
        return getResourceURL(resource, (ClassLoader)null);
    }

    public static URL getResourceURL(String resource, ClassLoader loader) throws IOException {
        URL url = classLoaderWrapper.getResourceAsURL(resource, loader);
        if (null == url) {
            throw new IOException("Could not find resource " + resource);
        }
        return url;
    }


    /**
     * 从CLASSPATH下获取InputStream
     * @param resource
     * @return
     * @throws IOException
     */
    public static InputStream getResourceAsStream(String resource) throws IOException {
        return getResourceAsStream(resource, (ClassLoader)null);
    }

    private static InputStream getResourceAsStream(String resource, ClassLoader classLoader) throws IOException {
        InputStream in = classLoaderWrapper.getResourceAsStream(resource);
        if (null == in) {
            throw new IOException("Could not find resource " + resource);
        }
        return in;
    }
}
